#!/usr/bin/env bash

SELFDIR=$(cd $(dirname "${BASH_SOURCE[0]}");pwd)

function main()
{
    # 通过路径回朔找到 g4 文件
    local g4_dir="${SELFDIR}"
    while [[ 0 -eq 0 ]]; do
        # 避免死循环
        if [[ "${g4_dir}" == "/" || "${g4_dir}" == "" ]]; then
            return  1
        fi

        # 如果找到 g4 文件
        if [[ -f "${g4_dir}/SA.g4" ]]; then
            break
        fi

        g4_dir=$(dirname "${g4_dir}")
    done

    local language="Go"
    cd  "${SELFDIR}" && antlr4 -Dlanguage="${language}" -package SA "${g4_dir}/SA.g4" -visitor -o "${SELFDIR}"
    RESULT=$?
    rm -rf "${SELFDIR}"/*.interp "${SELFDIR}"/*.tokens
    if [[ ${RESULT} -ne 0 ]]; then
        echo    "Error: Generate parser from 'SA.g4' failed(${RESULT})"
        return  2
    fi

    echo    "Generate parser from 'SA.g4' success"
    return 0
}

main    "$@"
exit    "$?"
